// pages/evaluate/evaluate.js
const app = getApp();
const api = require('../../utils/api');
const util = require('../../utils/util.js');
const constant = require('../../utils/constant');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //获取全局变量 导航栏的高度statusBarHeight
    statusBarHeight: app.globalData.statusBarHeight,
    // 胶囊
    jiaonang: app.globalData.jiaonang, 
    navigationHeight: app.globalData.navigationHeight,
    BASEURLWWW:constant.BASEURLWWW,
    // tabNav
    tabNav:[
      {id:0,title:"待评价",num:5},
      {id:1,title:"已评价"}
    ],
    // tabNav索引
    current: 0,
    // 条件筛选：0(待评价)，1(已评价)
    is_comment: 0,
    // 分页
    pagination:{
      pageNum: 1,  //分页初始值，页号1
      pageSize: 10, //分页初始值，每页20条
      total: null
    },
    // 订单数据
    orderListData: [],
    // 没有更多数据提示
    isLastNotice: false,
    // 是否有数据
    haveData: true,
    // 评论弹窗
    popupShow: false,
    popup:{
      goods_pic: [],
      textareaValue: '',
      star: 5,
      goods_name: ''
    },
    wordStatus: '至少输入10个字',
    wordNum: 0,
    // 星星
    star:[
      {id:1,word:'非常不满意',status: true},
      {id:2,word:'不满意',status: true},
      {id:3,word:'一般',status: true},
      {id:4,word:'满意',status: true},
      {id:5,word:'非常满意',status: true},
    ],
    word: '非常满意',
    // 选择图片
    tempFilePaths: [],
    // 数据提交
    queryform:{
      goods_id: null,
      order_goods_id: null,
      order_no: '',
      is_anon: 0, // 是否匿名，0：不匿名，1：匿名
      content: '', // 评论内容
      image: [], // 晒图
      is_image: 0, // 0=无图 1=有图
      score: 5 // 评分 1~5
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    if(options.order){ // 评价表单

    }else{ // 评价列表
      this.getOrderCommentList();
    }
  },
  // 获取订单列表
  getOrderCommentList:function(){
    let orderListDataArr = this.data.orderListData;
    if(orderListDataArr.length == this.data.pagination.total){
      this.setData({
        isLastNotice: true,
      })
    }else{
      api.getOrderCommentList(this.data.is_comment,this.data.pagination).then(res => { // 0 待评价,1 已评价
        if(res.code == 0){
          if(res.data.data.total != 0){
            // 加唯一标识
            let i = 0;
            res.data.data.list.forEach(item => {
              item.id = i++;
              item.order_goods.forEach(node => {
                node.id = i++;
              })
              orderListDataArr.push(item);
            })
            this.setData({
              haveData: true,
              'pagination.total':  res.data.data.total,
              orderListData: orderListDataArr,
              isLastNotice: false,
            })
          }else{
            this.setData({
              haveData: false,
              orderListData: [],
              'pagination.total': null,
              isLastNotice: false,
            })
          }
        }else{
          this.setData({
            haveData: false
          })
        }
      })
    }
    
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 返回上一级
  back:function(){
    if(this.data.popupShow){
      this.setData({
        popupShow: false
      })
    }else{
      wx.reLaunch({
        url: '/pages/personal/personal'
      })
    }
  },
  onReachBottom:function(){
    
  },
  // 选项卡切换
  tabSwitch:function(e){
    this.setData({
      current: e.currentTarget.dataset.id
    })
  },
  // 选项卡滑动
  tabChange:function(e){
    let pagination = {
      pageNum: 1,  //分页初始值，页号1
      pageSize: 10, //分页初始值，每页20条
      total: null
    }
    if(e.detail.current == 0){
      this.setData({
        is_comment: 0,
        current: e.detail.current,
        orderListData: [],
        pagination
      })
    }
    if(e.detail.current == 1){
      this.setData({
        is_comment: 1,
        current: e.detail.current,
        orderListData: [],
        pagination
      })
    }
    this.getOrderCommentList();
    
  },
  // 上拉加载
  bindscrolltolower:function(){
    let pagination = this.data.pagination;
    pagination.pageNum++;
    this.setData({
      pagination
    })
    this.getOrderCommentList();
  },
  // 去评价
  handleEvaluate:function(e){
    let goods = e.currentTarget.dataset.item;
    this.setData({
      'popup.goods_pic': goods.goods_pic,
      'popup.goods_name': goods.goods_name,
      popupShow: true,
      'queryform.goods_id': goods.goods_id,
      'queryform.order_goods_id': goods.order_goods_id,
      'queryform.order_no': goods.order_no
    })
  },
  // 评论文本框输入
  textareaInput:function(e){
    let value = util.trimStr(e.detail.value)
    let dValue = 10 - value.length;
    let wordStatus = '';
    if(dValue <=0 ){
      wordStatus = ''
    }else{
      wordStatus = '(还差'+ dValue +'个字)'
    }
    this.setData({
      wordStatus: wordStatus,
      wordNum: value.length,
      'popup.textareaValue': value
    })
  },
  // 星星
  star:function(e){
    let that = this;
    let starArr = this.data.star; 
    let index = e.currentTarget.dataset.index;
    let word = e.currentTarget.dataset.word;
    starArr.forEach(item => {
      if(item.id <= index){
        item.status = true;
      }else{
        item.status = false
      }
    })
    this.setData({
      star: starArr,
      word: word,
      'popup.star': index
    })
  },
  // 上传图片
  upload:function(){
    let that = this;
    let tempFilePaths = this.data.tempFilePaths;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success (res) {
        // tempFilePath可以作为img标签的src属性显示图片
        wx.uploadFile({
          url: 'https://api.changlejiuhang.com/myfile/wechat', //仅为示例，非真实的接口地址
          filePath: res.tempFilePaths[0],
          name: 'file',
          formData: {
            'user': 'test'
          },
          success (res){
            let jsonObj = JSON.parse(res.data)
            if(jsonObj.code == 0){
              tempFilePaths.push(jsonObj.data);
              that.setData({
                tempFilePaths
              })
            }
          }
        })
      }
    })
  },
  // 移除图片
  removeImg:function(e){
    let index = e.currentTarget.dataset.index;
    let tempFilePaths = this.data.tempFilePaths;
    tempFilePaths.splice(index,1);
    this.setData({
      tempFilePaths
    })
  },
  // 发布评论
  release:function(){
    let that = this;
    let queryform = this.data.queryform
    let newQueryform = [];
    let popup = this.data.popup;
    let tempFilePaths = this.data.tempFilePaths;
    let is_comment = this.data.is_comment;
    if(util.checkEmpty(popup.textareaValue)){
      wx.showToast({
        title: '请填写商品评价',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if(this.data.wordNum<10){
      wx.showToast({
        title: '评价不能少于10个字',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    // 数据组装
    
    if(is_comment == 0){
      queryform.content = popup.textareaValue;
      queryform.score = popup.star;
      if(tempFilePaths.length > 0){
        queryform.image = tempFilePaths;
        queryform.is_image = 1;
      }
      newQueryform = queryform;
    }else{
      newQueryform.goods_id = queryform.goods_id;
      newQueryform.order_goods_id = queryform.order_goods_id;
      newQueryform.order_no = queryform.order_no;
      newQueryform.is_anon = queryform.is_anon;
      newQueryform.content = popup.textareaValue;
    }
  
    api.addComment(newQueryform).then(res => {
      if(res.code == 0){
        let emptyQueryform = {
          goods_id: null,
          order_goods_id: null,
          order_no: '',
          is_anon: 0, // 是否匿名，0：不匿名，1：匿名
          content: '', // 评论内容
          image: [], // 晒图
          is_image: 0, // 0=无图 1=有图
          score: 5 // 评分 1~5
        }
        this.setData({
          queryform: emptyQueryform,
          popupShow: false,
          'pagination.total':  null,
          'pagination.pageNum': 1,
          orderListData: []
        })
        wx.showToast({
          title: '评论成功',
          icon: 'success'
        })
        that.getOrderCommentList();
      }
    })
    // wx.showToast({
    //   title: '评价成功',
    //   icon: 'none',
    //   duration: 2000,
    //   success:function(){
    //     that.setData({
    //       popupShow: false,
    //     })
    //   }
    // })
  },
  // 跳转到商品详情
  jumpToGoods:function(e){
    wx.reLaunch({
      url: '/pages/goods/goods?goods_id=' + e.currentTarget.dataset.goodsid
    })
  }
})